package com.vcredit.creditcat.manager;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.vcredit.creditcat.api.IContactManager;
import com.vcredit.creditcat.dto.Linkman;
import com.vcredit.creditcat.dto.LinkmansSource;
import com.vcredit.creditcat.model.AddressList;
import com.vcredit.creditcat.service.AddressListService;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.EmojiUtil;

@Service(protocol = { "protocol1" }, version = "1.0")
public class ContactManager implements IContactManager {

	@Autowired
	private AddressListService addressListService;

	@Log
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Boolean saveAddressLists(Long custId, LinkmansSource source) throws Exception {
		List<Linkman> linkmans = source.getLinkmans();
		// 将爬取的联系人转换为AddressList对象
		List<AddressList> addrs = new ArrayList<AddressList>();
		for (Linkman linkman : linkmans) {
			try {
				AddressList addr = new AddressList(custId, 
						Utility.clearBlank(EmojiUtil.filterEmoji(linkman.getName())),
						Utility.formatPhoneNo(EmojiUtil.filterEmoji(linkman.getMobileNo()), false));
				addrs.add(addr);
			} catch (Exception e) {
				continue;
			}
		}
		//查询改手机号是否存在，如果存在则跳过本次循环
		List<AddressList> addrBook = addressListService.findByCustId(custId);
		List<AddressList> realInsertRecords = increment(addrs, addrBook);
		if(null != realInsertRecords && !realInsertRecords.isEmpty()){
			for (AddressList addressList : realInsertRecords) {
				try {
					addressListService.insert(addressList);
				} catch (Exception e) {
					continue;
				}
			}
		}
		return true;
	}
	
	
	private List<AddressList> increment(List<AddressList> more, List<AddressList> dbData) {
		if(more.isEmpty()||dbData.isEmpty()){
			return more;
		}
		List<AddressList> result = new ArrayList<AddressList>();
		Set<AddressList> setMore = new HashSet<AddressList>();
		Set<AddressList> setDbData = new HashSet<AddressList>();
		Set<AddressList> resultData = new HashSet<AddressList>();
		CollectionUtils.addAll(setMore, more);   
		CollectionUtils.addAll(setDbData, dbData);
		resultData.addAll(setMore);
		resultData.removeAll(setDbData);
		result.addAll(resultData);
		return result;
	}
}
